package com.lk.security.authentication.mobile;

import com.lk.security.authentication.CustomAuthenticationFailureHandler;
import com.lk.security.authentication.exception.ValidateCodeException;
import com.lk.security.controller.MobileLoginController;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @program: lk-security-parent
 * @description: 手机短信验证码过滤器
 * @author: Aspirin
 * @create: 2020-05-30 22:30
 */
@Component("mobileValidateFilter")
public class MobileValidateFilter extends OncePerRequestFilter {

  @Autowired CustomAuthenticationFailureHandler customAuthenticationFailureHandler;

  @Override
  protected void doFilterInternal(
      HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
      throws ServletException, IOException {
    // 1.判断请求的路径
    String mobileSubmitUrl = "/mobile/form";
    String requestType = "POST";
    if (mobileSubmitUrl.equals(request.getRequestURI())
        && requestType.equalsIgnoreCase(request.getMethod())) {
      try {
        // 校验验证码合法性
        validate(request);
      } catch (AuthenticationException e) {
        // 交给失败处理器进行处理异常
        customAuthenticationFailureHandler.onAuthenticationFailure(request, response, e);
        //  一定要记得结束
        return;
      }
    }
    // 放行
    filterChain.doFilter(request, response);
  }

  private void validate(HttpServletRequest request) {
    String sessionCode =
        (String) request.getSession().getAttribute(MobileLoginController.SESSION_KEY);
    // 获取用户输入的验证码
    String inputCode = request.getParameter("code");
    // 判断是否正确 首先判空
    if (StringUtils.isBlank(inputCode)) {
      throw new ValidateCodeException("验证码不能为空");
    }
    if (!inputCode.equalsIgnoreCase(sessionCode)) {
      throw new ValidateCodeException("验证码输入错误");
    }
  }
}
